<template>
    <div class="app-container">
        <div class="info-main" :class="{'thin':UIState.adMode}">
            <div class="filter-container ">
                <el-radio-group v-model="UIState.adMode">
                    <el-radio-button :label="false">信息管理</el-radio-button>
                    <el-radio-button :label="true">广告位管理</el-radio-button>
                </el-radio-group>
            </div>


            <div class="filter-container clearfix">
                <el-select class="type-select" v-model="params.category" placeholder="选择分类">
                    <el-option
                            label="所有分类"
                            value="">
                    </el-option>
                    <el-option
                            v-for="item in industries"
                            :key="item.name"
                            :label="item.name"
                            :value="item.name">
                    </el-option>
                </el-select>

                <el-input
                        placeholder="搜索"
                        icon="search"
                        class="search-input"
                        v-model="params.title">
                </el-input>

                <el-dropdown class="fr" trigger="click" v-if="!UIState.adMode">
                    <el-button >
                        列表选项<i class="el-icon-caret-bottom el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-checkbox-group
                                v-model="checkedColumns">
                            <div class="checkbox-item" v-for="item in columns"
                                 :key="item.prop">
                                <el-checkbox :label="item.prop">{{item.label}}</el-checkbox>
                            </div>
                        </el-checkbox-group>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>

            <el-table v-if="!UIState.adMode" class="table-compact" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" stripe fit
                      highlight-current-row>
                <el-table-column align="center" label="#"
                                 width="100">
                    <template scope="scope">
                        <div  class="img" v-lazy:background-image.container="scope.row.images[0]"></div>
                    </template>
                </el-table-column>
                <el-table-column
                        width="200"
                        label="标题">
                    <template scope="scope">
                        <div class="title line-clamp-2" :title="scope.row.title">
                            <a :href="baseURL+'/'+subDomain+'/detail/'+scope.row._id" target="_blank">{{scope.row.title}}</a>
                        </div>
                    </template>
                </el-table-column>

                    <el-table-column
                            v-if="checkedProps.type"
                            label="分类">
                        <template scope="scope">
                            <el-tag type="primary">{{scope.row.estate.type}}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            v-if="checkedProps.area"
                            prop="estate.area"
                            label="面积">
                        <template scope="scope">
                            <span>{{scope.row.estate.area}}m<sup>2</sup></span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            v-if="checkedProps.transferFee"
                            prop="estate.transferFee"
                            label="转让费">
                        <template scope="scope">
                    <span>{{scope.row.estate.transferFee}}
                        <template v-if="scope.row.estate.offset>0">± {{scope.row.estate.offset}}</template>元</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            v-if="checkedProps.rental"
                            prop="estate.rental"
                            label="租金">
                        <template scope="scope">
                            <span>{{scope.row.estate.rental}} 元/月</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="estate.station"
                            v-if="checkedProps.station"
                            label="地铁站点">
                        <template scope="scope">
                            <span>{{scope.row.estate.subway}} - {{scope.row.estate.station}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            v-if="checkedProps.traded"
                            label="状态">
                        <template scope="scope">
                            <el-tag v-if="scope.row.isTraded" type="success">已成交</el-tag>
                            <el-tag v-else>未成交</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column
                            width="160"
                            v-if="checkedProps.createdAt"
                            prop="createdTime"
                            label="添加时间">
                        <template scope="scope">
                            <span class="time">{{scope.row.createdTime}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="操作">
                        <template scope="scope">
                            <el-button v-if="scope.row.isTraded === true" @click="changeTradedFalse(scope.row._id)" type="text" >上线</el-button>
                            <el-button v-if="scope.row.isTraded === false" @click="changeTradedTrue(scope.row._id)" type="text" >成交</el-button>
                            <router-link :to="'/info/edit/'+scope.row._id">
                                <el-button type="text" >编辑</el-button>
                            </router-link>
                            <el-button @click="deleteInfo(scope.row._id)" type="text" >删除</el-button>
                        </template>
                    </el-table-column>
            </el-table>


            <div  v-if="UIState.adMode"
                  class="info-source-list"
                 v-dragula="list" bag="dragBag">
                <div v-for="item in list"
                     track-by="$index"
                     :key="item._id"
                     class="info-item"
                     data-source="true"
                >
                    <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                    <h5 class="line-clamp-2">{{item.title}}</h5>
                    <div class="handle" >
                        <icon-svg style="pointer-events: none" icon-class="untitled6"></icon-svg>
                    </div>
                    <div class="area"><strong>{{item.estate.area}}</strong>m<sup>2</sup></div>
                    <div class="rental"><strong>{{item.estate.rental}}</strong> 元/月</div>
                </div>
            </div>


            <el-pagination
                    @size-change="handleSizeChange"
                    :current-page.sync="pageInfo.pageIndex"
                    :page-sizes="[30, 50, 100]"
                    :page-size="pageInfo.pageSize"
                    :layout="UIState.adMode ? 'pager' : 'total, sizes, prev, pager, next, jumper'"
                    :total="pageInfo.totalCount">
            </el-pagination>
        </div>


        <div class="ad-layout"
             v-if="UIState.adMode">
            <div class="layout-section">
                <el-button class="save-btn" @click="saveAdsenses" size="small" type="primary">保存</el-button>

                <el-tabs v-model="UIState.tabActiveName">
                <el-tab-pane label="首页" name="home">
                        <h3>最新爆料</h3>
                        <el-row>
                            <el-col class="list-big-con" :span="8">
                                <h4>大图<div  class="fr" @click="UIState.HomeNewPanel=!UIState.HomeNewPanel">more</div></h4>
                                <div v-dragula="adLayout.HomeNew" bag="dragBag"
                                     data-config="HomeNew"
                                     class="new-list" :class="{'open':UIState.HomeNewPanel}">
                                    <div v-for="item in adLayout.HomeNew"
                                         :key="item._id"
                                         track-by="$index"
                                         class="info-item">
                                        <h5>{{item.title}}</h5>
                                        <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                    </div>
                                </div>
                            </el-col>
                            <el-col class="con" :span="16">
                                <h4>小图</h4>
                                <div v-dragula="adLayout.HomeNewSm" bag="dragBag"
                                     data-config="HomeNewSm"
                                     class="new-sm-list">
                                    <div v-for="item in adLayout.HomeNewSm"
                                         :key="item._id"
                                         track-by="$index"
                                         class="info-item">
                                        <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                        <h5 class="line-clamp-2">{{item.title}}</h5>
                                        <div class="area">{{item.estate.area}}平 </div>
                                        <div class="rental">{{item.estate.rental}} 元/月</div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                        <h3>腾铺优选</h3>
                        <h4>大图</h4>
                        <el-row>
                            <div v-dragula="adLayout.HomeOpt" bag="dragBag"
                                 data-config="HomeOpt"
                                 class="opt-list">
                                <div v-for="item in adLayout.HomeOpt"
                                     :key="item._id"
                                     track-by="$index"
                                     class="info-item">
                                    <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                    <h5 class="line-clamp-2">{{item.title}}</h5>
                                    <div class="area">{{item.estate.area}}平 </div>
                                    <div class="rental">{{item.estate.rental}} 元/月</div>
                                </div>
                            </div>
                        </el-row>
                        <h4>小图</h4>
                        <el-row>
                            <div v-dragula="adLayout.HomeOptSm" bag="dragBag"
                                 data-config="HomeOptSm"
                                 class="opt-sm-list">
                                <div v-for="item in adLayout.HomeOptSm"
                                     :key="item._id"
                                     track-by="$index"
                                     class="info-item">
                                    <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                    <h5 class="line-clamp-2">{{item.title}}</h5>
                                    <div class="area">{{item.estate.area}}平 </div>
                                    <div class="rental">{{item.estate.rental}} 元/月</div>
                                </div>
                            </div>
                        </el-row>
                        <h4>无图</h4>
                        <el-row>
                            <div v-dragula="adLayout.HomeOptSmNo" bag="dragBag"
                                 data-config="HomeOptSmNo"
                                 class="opt-sm-no-list">
                                <div v-for="item in adLayout.HomeOptSmNo"
                                     :key="item._id"
                                     track-by="$index"
                                     class="info-item">
                                    <h5 class="line-clamp-2">{{item.title}}</h5>
                                    <div class="area">{{item.estate.area}}平 </div>
                                    <div class="rental">{{item.estate.rental}} 元/月</div>
                                </div>
                            </div>
                        </el-row>

                        <el-row>
                            <el-col :span="16">
                                <h4>一周快转</h4>
                                <div v-dragula="adLayout.HomeWeek"
                                     data-config="HomeWeek"
                                     class="week-list" bag="dragBag">
                                    <div v-for="item in adLayout.HomeWeek"
                                         :key="item._id"
                                         track-by="$index"
                                         class="info-item">
                                        <h5>{{item.title}}</h5>
                                        <div class="area">{{item.estate.area}}平 </div>
                                        <div class="rental">{{item.estate.rental}} 元/月</div>
                                    </div>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <h4>热门转让</h4>
                                <div v-dragula="adLayout.HomeHot"
                                     data-config="HomeHot"
                                     class="hot-list" bag="dragBag"
                                >
                                    <div v-for="item in adLayout.HomeHot"
                                         :key="item._id"
                                         track-by="$index"
                                         class="info-item">
                                        <h5 class="line-clamp-2">{{item.title}}</h5>
                                        <div class="area">{{item.estate.area}}平 </div>
                                        <div class="rental">{{item.estate.rental}} 元/月</div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                </el-tab-pane>
                <el-tab-pane label="搜索页" name="search">
                        <h3>推荐栏</h3>
                        <div v-dragula="adLayout.Search" bag="dragBag"
                             data-config="Search"
                             class="new-sm-list search-list">
                            <div v-for="item in adLayout.Search"
                                 :key="item._id"
                                 track-by="$index"
                                 class="info-item">
                                <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                <h5 class="line-clamp-2">{{item.title}}</h5>
                                <div class="area">{{item.estate.area}}平 </div>
                                <div class="rental">{{item.estate.rental}} 元/月</div>
                            </div>
                        </div>
                </el-tab-pane>
                <el-tab-pane label="详情页" name="detail">
                        <h3>大图</h3>
                        <div v-dragula="adLayout.Detail" bag="dragBag"
                             data-config="Detail"
                             class="opt-list detail-list">
                            <div v-for="item in adLayout.Detail"
                                 :key="item._id"
                                 track-by="$index"
                                 class="info-item">
                                <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                <h5 class="line-clamp-2">{{item.title}}</h5>
                                <div class="area">{{item.estate.area}}平 </div>
                                <div class="rental">{{item.estate.rental}} 元/月</div>
                            </div>
                        </div>
                        <h3>小图</h3>
                        <div v-dragula="adLayout.DetailSm" bag="dragBag"
                             data-config="DetailSm"
                             class="new-sm-list">
                            <div v-for="item in adLayout.DetailSm"
                                 :key="item._id"
                                 track-by="$index"
                                 class="info-item">
                                <div class="img" v-lazy:background-image.container="item.images[0]"></div>
                                <h5 class="line-clamp-2">{{item.title}}</h5>
                                <div class="area">{{item.estate.area}}平 </div>
                                <div class="rental">{{item.estate.rental}} 元/月</div>
                            </div>
                        </div>
                </el-tab-pane>
            </el-tabs>

            </div>



        </div>

    </div>
</template>

<script>
  import fetch from '@/utils/fetch';
  import {parseTime} from '@/utils';
  import industries from '@/data/industries.json';
  import AdLayout from '@/components/AdLayout';
  import draggable from 'vuedraggable';
  import Vue from 'vue';
  import adConfig from '@/data/adsenses.json';
  import ElButton from "../../../../node_modules/element-ui/packages/button/src/button";
  import { mapGetters } from 'vuex';

  export default {
    components: {
      ElButton,
      AdLayout,draggable},
    data() {
      return {
        list: [],
        adLayout: {
          HomeNew: [],
          HomeNewSm: [],
          HomeOpt: [],
          HomeOptSm: [],
          HomeOptSmNo: [],
          HomeWeek: [],
          HomeHot: [],
          Search: [],
          Detail: [],
          DetailSm: []
        },
        adConfig:adConfig,
        listLoading: true,
        checkedColumns: ['type','area','transferFee','rental', 'station', 'traded', 'createdAt'],
        columns: [
          { label: '分类', prop: 'type' },
          { label: '面积', prop: 'area' },
          { label: '转让费', prop: 'transferFee' },
          { label: '租金', prop: 'rental' },
          { label: '地铁站点', prop: 'station' },
          { label: '状态', prop: 'traded' },
          { label: '添加时间', prop: 'createdAt' },
        ],
        industries: industries,
        params: {
          title: '',
          category: ''
        },
        UIState: {
          adMode: false,
          HomeNewPanel: false,
          tabActiveName: 'home'
        },

        pageInfo: {
          pageIndex: 1,
          pageSize: 50,
          totalCount: 0
        },
        subDomain: '',
        baseURL: ''
      }
    },
    watch: {
      'pageInfo.pageIndex': 'fetchData',
      'pageInfo.pageSize': 'fetchData',
      params: {
        handler: function () {
          this.fetchData();
        },
        deep: true
      },
        'adLayout':{
            handler: function (val,oldVal) {
                Object.keys(val).forEach( key=>{
                    if(this.adLayout[key].length>this.adConfig[key].size){
                        this.adLayout[key].pop();
                    }
                });

            },
            deep: true
        }
    },
    created() {
        this.baseURL = process.env.BASE_API;
        this.subDomain = this.site_subDomain;
        console.log(this.site_subDomain);
      this.fetchData().then(this.getAdsenses());
      if (!Vue.vueDragula.find('dragBag')) {
        Vue.vueDragula.options('dragBag', {
          copy: function(el, source) {
            return el.dataset.source === 'true';
          },
          accepts: function(el, target, source, sibling) {
            return target.className !== 'info-source-list';
          },
          moves: function(el, container, handle) {
            if(container.className === 'info-source-list'){
              return handle.classList.contains('handle');
            }else {
              return true;
            }
          }

        })
      }
    },
    computed: {
      ...mapGetters([
        'site',
        'site_subDomain'
      ]),
      checkedProps:function () {
        let obj = {};
        this.checkedColumns.forEach((item)=>{
          obj[item] = true
        })
        return obj
      }
    },
    methods: {


      fetchData() {
        this.listLoading = true;
        const q = {
          query: {
            infoType: 'Attorn',
            estateType: 'Store',
            infoSource: 'TENGPU',
            site: this.site
          },
          sort: {
            createdAt: -1
          },
          page: {
            index: this.pageInfo.pageIndex,
            size: this.pageInfo.pageSize
          }
        };
        this.params.title && (q.query.title = this.params.title);
        this.params.category && (q.query.category = this.params.category);

        return fetch({
          url: '/infos',
          method: 'get',
          params: {
            q:q
          }
        }).then(res => {
          res.data.pageDatas.forEach((item) => {
            item.createdTime = parseTime(new Date(item.createdAt).getTime(),'{y}-{m}-{d} {h}:{i}');
          });
          this.list = res.data.pageDatas;
          console.log(res.data.pageDatas);
          this.pageInfo.totalCount = res.data.pageInfo.totalCount;
          this.listLoading = false;
        })

//        getList(this.listQuery).then(response => {
//          this.list = response.data.items;
//          this.listLoading = false;
//        })
      },
      getSite() {
          fetch({
            url: '/site/' + this.site + '/adsenses',
            method: 'get',
          }).then(res => {
            Object.assign(this.adLayout, res.data)
          });
      },
      getAdsenses() {
        fetch({
          url: '/site/' + this.site,
          method: 'get',
        }).then(res => {
            console.log(res.data);
        });
      },
      deleteInfo(id) {
        this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          fetch({
            url: '/info/' + id,
            method: 'DELETE'
          }).then(res => {
            if (res.data.ok === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.$delete(this.list, this.list.indexOf(this.list.find(item => {
                return item._id === id;
              })))
            }
          });
        })
      },
      changeTradedTrue(id) {
          this.$confirm('此操作将此条信息设为成交, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            fetch({
              url: '/info/'+id+'/offline',
              method: 'put'
            }).then(res => {
                console.log(res)
              if (res.status === 200) {
                this.$message({
                  type: 'success',
                  message: '信息设为成交!'
                });
                this.$set( this.list[this.list.indexOf(this.list.find(item => {
                    return item._id === id
                }))], 'isTraded', true);
                // this.$delete(this.list, this.list.indexOf(this.list.find(item => {
                //   return item._id === id;
                // })))
              }
            });
          })
      },
      changeTradedFalse(id) {
          this.$confirm('此操作此条信息设为未成交, 是否继续?', '提示', {
            type: 'warning'
          }).then(() => {
            fetch({
              url: '/info/'+id+'/offline',
              method: 'put'
            }).then(res => {
                console.log(res)
              if (res.status === 200) {
                this.$message({
                  type: 'success',
                  message: '信息设为未成交!'
                });
                this.$set( this.list[this.list.indexOf(this.list.find(item => {
                    return item._id === id
                }))], 'isTraded', false);
                // this.$delete(this.list, this.list.indexOf(this.list.find(item => {
                //   return item._id === id;
                // })))
              }
            });
          })
      },
      saveAdsenses() {
        let data = {};
        Object.keys(this.adLayout).forEach(key=>{
          data[key] = this.adLayout[key].map(el=>{
            return el._id
          })
        });

        fetch({
          url: '/site/' + this.site + '/adsenses',
          method: 'put',
          data:data
        }).then(res => {
          if (res.data.ok === 1) {
            this.$message({
              type: 'success',
              message: '更新成功!'
            });
          }
        });

      },

      handleSizeChange(val) {
        this.pageInfo.pageSize = val;
      }
    }
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .checkbox-item{
        display: block;
        margin: 6px 20px 6px 10px;
    }
    .time{
        word-break:break-all ;
    }
    .search-input{
        width: 300px;
    }
    .info-main{
        &.thin{
            width: 320px;
            .type-select{
                width: 120px;
            }
            .search-input{
                width: 195px;
            }
        }
    }
    .ad-layout{
        position: fixed;
        width: calc(100% - 360px);
        top: 60px;
        right: 0;
        bottom: 0;
        background-color: #333744;
        overflow-y: scroll;



        .list-big-con{
            width: 290px;
            height: 228px;
            position: relative;
        }


        .layout-section{
            background-color: #fff;
            border: 1px solid #eaeefb;
            border-radius: 4px;
            margin: 0 auto;
            padding: 10px;
            width: 900px;
            position: relative;

            .save-btn{
                position: absolute;
                right: 15px;
                top: 15px;
                z-index: 999;
            }

            h3{
                margin: 0 0 10px 0;
                padding: 10px;
                text-align: center;
                color: #a46497;
                border-bottom: 1px solid #ddd;
            }

            h4{
                margin: 0 0 10px 0;
                padding: 4px;
                text-align: center;
                border-bottom: 1px dashed #ddd;
            }
            .list{
                min-height: 100px;
            }
        }
    }


    .img{
        margin: 8px 0;
        width: 80px;
        height: 60px;
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center;
        &[lazy=error],&[lazy=loading]{
            background-size: 50%;
        }
    }
    .info-item{
        position: relative;
        display: block;
        border: 1px solid #d1dbe5;
        width: 150px;
        height: 120px;
        border-radius: 4px;
        background-color: #ddd;
        overflow: hidden;
        padding:5px 10px;
        box-shadow: 0 2px 4px 0 rgba(0,0,0,.12), 0 0 6px 0 rgba(0,0,0,.04);
        .handle{
            position: absolute;
            top:6px;
            left:4px;
            padding: 5px;
            cursor: all-scroll;
        }
        &::before{
            position: absolute;
            top: 30px;
            left: 60px;
            content: '松开释放';
        ;
        }
        .img,h5,.area,.rental{
            display: none;
        }
    }
    .info-source-list{
        .info-item{
            position: relative;
            border: 1px solid #d1dbe5;
            border-radius: 4px;
            width: auto;
            height: auto;
            background-color: #fff;
            overflow: hidden;
            box-shadow: 0 2px 4px 0 rgba(0,0,0,.12), 0 0 6px 0 rgba(0,0,0,.04);
            margin: 10px 0;
            padding:5px 10px;
            &::before{
                display: none;
            }
            .img{
                display: block;
                float: left;
                margin-right: 10px;
                margin-left: 25px;
            }

            h5{
                display: block;
                margin: 6px 0;
                font-size: 14px;
                height: 38px;
                line-height: 19px;
            }
            .area{
                display: inline-block;
                strong{
                    color: #a46497;
                }
            }
            .rental{
                display: inline-block;
                strong{
                    color: #a46497;
                }
            }
        }
    }

    .new-sm-list,.opt-sm-list,.opt-sm-no-list,.week-list,.hot-list{
        min-height: 158px;
        background-color: #eee;
        .info-item{
            display:inline-block;
            width: 282px;
            height: 70px;
            padding: 5px;
            margin: 3px;
            border: 0;
            box-shadow: none;
            border-radius: 0;
            background-color: #fff;
            font-size: 12px;
            &::before{
                display: none;
            }
            .img {
                display: block;
                float: left;
                width: 80px;
                height: 60px;
                margin: 0 5px 0 0;
            }
            h5{
                display: block;
                margin: 0 0 10px 0;
            }
            .area{
                display: inline-block;
            }
            .rental{
                display: inline-block;
            }
        }
    }
    .opt-sm-list{
        height: 154px;
    }
    .week-list{
        margin-right: 5px;
    }

    .opt-sm-list,.opt-sm-no-list{
        .info-item {
            width: 284px;
            height: 70px;
            padding: 5px;
            &::before{
                display: none;
            }
        }
    }




    .new-list,.opt-list{
        width: 285px;
        height: 228px;
        background-color: #eee;
        margin-right: 5px;
        overflow: hidden;
        &.open{
            width:872px;
            box-shadow: 0 0 10px rgba(0,0,0,0.5);
        }
        .info-item{
            width: 100%;
            height: 100%;
            display: inline-block;
            position: relative;
            border: 0;
            border-radius: 0;
            box-shadow: none;
            padding: 0;
            &::before{
                display: none;
            }
            .img{
                display: block;
                width: 100%;
                height: 100%;
                margin: 0;
            }
            h5{
                display: block;
                position: absolute;
                left: 0;
                bottom: 0;
                color: #fff;
                margin: 5px;
            }
        }
    }
    .opt-list{
        width:872px;
        border: 0;
        height: 243px;

        .info-item{
            &::before{
                display: none;
            }
            margin: 10px;
            width: 270px;
            height: 220px;
        }
    }
    .search-list{
        height: 80px;
    }

    .detail-list{
        height: 490px;
    }


</style>
